﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;

namespace Framework.WebmasterTool.FileManagers
{
    public partial class UploadFile : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                LoadUsers();
                LoadFiles();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.DownloadFile.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void LoadUsers()
        {
            var users = entity.udv_Users.Select(us => new { us.UserID, us.UserName }).ToList();
            ddlUser.DataValueField = "UserID";
            ddlUser.DataTextField = "UserName";
            ddlUser.DataSource = users;
            ddlUser.DataBind();
        }

        public void LoadFiles()
        {
            if (Request.QueryString["FileID"] != null)
            {
                int fileID;
                int.TryParse(Request.QueryString["FileID"].ToString(), out fileID);
                var file = entity.udv_Files.Where(fi => fi.FileID == fileID).FirstOrDefault();
                file.aspnet_UsersReference.Load();
                if (file != null)
                {
                    txtTitle.Text = file.Title;
                    txtTitle_en.Text = file.Title_en;
                    txtDescription.Text = file.Description;
                    txtDescription_en.Text = file.Description_en;
                    ddlUser.SelectedValue = file.aspnet_Users.UserId.ToString();
                    txtDisplayOrder.Text = file.DisplayOrder.Value.ToString();
                    chkIsActive.Checked = file.IsActive.Value;
                    lblFileType.Text = file.FileType;
                    lblFileSize.Text = file.FileSize.ToString() + " KB";
                    lblAddedDate.Text = String.Format("{0:dd/MM/yyyy HH:mm:ss tt}", file.AddedDate);
                    lblAddedBy.Text = file.AddedBy;
                    lblUpdatedDate.Text = String.Format("{0:dd/MM/yyyy HH:mm:ss tt}", file.UpdatedDate);
                    lblUpdatedBy.Text = file.UpdatedBy;
                    aDownload.HRef = ConfigPaths.Path_FileDownload_Folder + file.FileURL;
                    if (Globals.CheckExtensionImage(file.FileURL))
                    {
                        imgImage.Src = ConfigPaths.Path_FileDownload_Folder + file.FileURL;
                    }
                }
                else
                {
                    Response.Redirect("Default.aspx");
                }
            }
            else
            {
                lblFileType.Text = "None";
                lblFileSize.Text = "None";
                lblAddedBy.Text = "None";
                lblAddedDate.Text = "None";
                lblUpdatedBy.Text = "None";
                lblUpdatedDate.Text = "None";
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (ddlUser.SelectedValue == "0")
            {
                lblMessage.Text = "Chưa chọn Username";
            }
            else
            {
                if (Request.QueryString["FileID"] != null)
                {
                    int fileID;
                    int.TryParse(Request.QueryString["FileID"].ToString(), out fileID);
                    var file = entity.udv_Files.Where(fi => fi.FileID == fileID).FirstOrDefault();
                    if (file != null)
                    {
                        string oldTitle = file.Title;
                        file.Title = txtTitle.Text;
                        file.Title_en = txtTitle_en.Text;
                        file.Description = txtDescription.Text;
                        file.Description_en = txtDescription_en.Text;
                        Guid userID = new Guid(ddlUser.SelectedValue);
                        file.aspnet_Users = entity.aspnet_Users.Where(us => us.UserId == userID).FirstOrDefault();
                        file.DisplayOrder = int.Parse(txtDisplayOrder.Text);
                        file.IsActive = chkIsActive.Checked;
                        if (FileUpload1.HasFile)
                        {
                            if (FileUpload1.PostedFile.ContentLength > (1024 * 1024 * 5))
                            {
                                lblMessage.Text = "Dung lượng file upload quá lớn, sử dụng file có kích thước < 5MB";
                                return;
                            }
                            file.FileType = FileUpload1.PostedFile.ContentType + " | " + System.IO.Path.GetExtension(FileUpload1.FileName).Substring(1);
                            file.FileSize = FileUpload1.PostedFile.ContentLength / 1024;
                            Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_FileDownload_Folder_MapPath + file.FileURL));
                            string fileName = Globals.GetFileName(FileUpload1.FileName);
                            FileUpload1.SaveAs(Server.MapPath(ConfigPaths.Path_FileDownload_Folder_MapPath + fileName));
                            file.FileURL = fileName;
                        }
                        file.UpdatedBy = Membership.GetUser().UserName;
                        file.UpdatedDate = DateTime.Now;
                        entity.SaveChanges();
                        //create db log
                        CreateDBLog(null, null, TypeAction.Update, "Cập nhật quản lý file: " + oldTitle + " - " + file.Title, file.Description, "", "", "",
                                file.IsActive.Value.ToString(), "", "", "");
                    }
                }
                else
                {
                    if (!FileUpload1.HasFile)
                    {
                        lblMessage.Text = "Bạn chưa chọn file để upload";
                        return;
                    }
                    else
                    {
                        if (FileUpload1.PostedFile.ContentLength > (1024 * 1024 * 5))
                        {
                            lblMessage.Text = "Dung lượng file upload quá lớn, sử dụng file có kích thước < 5MB";
                            return;
                        }
                        udv_Files file = new udv_Files();
                        file.Title = txtTitle.Text;
                        file.Title_en = txtTitle_en.Text;
                        file.Description = txtDescription.Text;
                        file.Description_en = txtDescription_en.Text;
                        Guid userID = new Guid(ddlUser.SelectedValue);
                        file.aspnet_Users = entity.aspnet_Users.Where(us => us.UserId == userID).FirstOrDefault();
                        file.DisplayOrder = int.Parse(txtDisplayOrder.Text);
                        file.IsActive = chkIsActive.Checked;
                        file.FileType = FileUpload1.PostedFile.ContentType + " | " + System.IO.Path.GetExtension(FileUpload1.FileName).Substring(1);
                        file.FileSize = FileUpload1.PostedFile.ContentLength / 1024;
                        file.AddedBy = Membership.GetUser().UserName;
                        file.AddedDate = DateTime.Now;
                        file.UpdatedBy = Membership.GetUser().UserName;
                        file.UpdatedDate = DateTime.Now;
                        string fileName = Globals.GetFileName(FileUpload1.FileName);
                        FileUpload1.SaveAs(Server.MapPath(ConfigPaths.Path_FileDownload_Folder_MapPath + fileName));
                        file.FileURL = fileName;
                        file.TotalViews = 0;
                        file.IsActive = true;
                        entity.AddToudv_Files(file);
                        entity.SaveChanges();

                        //create db log
                        CreateDBLog(null, null, TypeAction.Insert, "Tạo quản lý file: " + file.Title, file.Description, "", "", "",
                                file.IsActive.Value.ToString(), "", "", "");
                    }
                }
                //data cache
                Cache.Remove("File");
                Response.Redirect("Default.aspx");
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("Default.aspx");
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}